package com.android.photoassistant;

import java.util.ArrayList;

import com.google.android.gms.internal.ay;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class MainActivity extends TabActivity {

	private enum TYPE_EXIT{LOGIN_DIALOG, ACTIVITY}
	private enum REGIST_RESULT{NONE, REGIST_SUCCESSFULLY, REGIST_ERROR}
	private Handler handler;
	private Handler progHandler;
	private Handler registeHandle;
	private REGIST_RESULT registResult = REGIST_RESULT.NONE;
	private ArrayList<User> userList;
	private boolean flagCheckLogin = false;
	private Runnable runnable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        userList = new ArrayList<User>();
        User user1 = new User();
        user1.setMail("quang612005@gmail.com");
        user1.setPassword("123456");
        userList.add(user1);
        
        progHandler = new Handler();
        
		final Runnable progRunnable = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				progHandler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						AsyncTask<Void, Void, Void> progressTask = new AsyncTask<Void, Void, Void>() {
							
							private ProgressDialog pd;
							@Override
							protected void onPostExecute(Void result) {
								// TODO Auto-generated method stub
								pd.dismiss();
							}

							@Override
							protected void onPreExecute() {
								// TODO Auto-generated method stub
								pd = new ProgressDialog(MainActivity.this);
								pd.setTitle("Processing");
								pd.setMessage("Please wait.");
								pd.setCancelable(false);
								pd.setIndeterminate(true);
								pd.show();
							}

							@Override
							protected Void doInBackground(
									Void... params) {
								// TODO Auto-generated method stub
								try {
									for (int i = 0; i < 4; i++) {
										if (flagCheckLogin == false) {
											Thread.sleep(5000);
										} else {
											break;
										}
									}
									if (flagCheckLogin == false) {
										final AlertDialog.Builder alertDialogLoginFaile = new AlertDialog.Builder(MainActivity.this);
										alertDialogLoginFaile.setTitle("Error");
										alertDialogLoginFaile.setMessage("Login fail");
										
										alertDialogLoginFaile.setCancelable(false);
										
										alertDialogLoginFaile.setPositiveButton("Re-Login", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												new Thread(runnable).start();
											}
										});
										alertDialogLoginFaile.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												System.exit(0);
											}
										});
										
										MainActivity.this.runOnUiThread(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												AlertDialog dialogLoginError = alertDialogLoginFaile.create();
												dialogLoginError.show();
											}
										});
										
									} else {
										final AlertDialog.Builder alertDialogLoginSuccess = new AlertDialog.Builder(MainActivity.this);
										alertDialogLoginSuccess.setTitle("Success");
										alertDialogLoginSuccess.setMessage("Login successfully");
										
										alertDialogLoginSuccess.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												dialog.dismiss();
											}
										});
										
										alertDialogLoginSuccess.setCancelable(false);
										
										
										MainActivity.this.runOnUiThread(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												AlertDialog dialogLoginSuccess = alertDialogLoginSuccess.create();
												dialogLoginSuccess.show();
											}
										});
									}
								} catch (Exception e) {
									// TODO: handle exception
									e.printStackTrace();
								}
								return null;
							}
						};
						progressTask.execute((Void[])null);
					}
				});
			}
		};
		
		registeHandle = new Handler();
		final Runnable registRunnable = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				progHandler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						AsyncTask<Void, Void, Void> progressTask = new AsyncTask<Void, Void, Void>() {
							
							private ProgressDialog pd;
							@Override
							protected void onPostExecute(Void result) {
								// TODO Auto-generated method stub
								pd.dismiss();
							}

							@Override
							protected void onPreExecute() {
								// TODO Auto-generated method stub
								pd = new ProgressDialog(MainActivity.this);
								pd.setTitle("Register");
								pd.setMessage("Please wait...");
								pd.setCancelable(false);
								pd.setIndeterminate(true);
								pd.show();
							}

							@Override
							protected Void doInBackground(
									Void... params) {
								// TODO Auto-generated method stub
								try {
									for (int i = 0; i < 4; i++) {
										if (registResult == REGIST_RESULT.NONE) {
											Thread.sleep(5000);
										} else {
											break;
										}
									}
									if (registResult == REGIST_RESULT.REGIST_SUCCESSFULLY) {
										final AlertDialog.Builder alertDialogRegisteSuccess = new AlertDialog.Builder(MainActivity.this);
										alertDialogRegisteSuccess.setTitle("Register");
										alertDialogRegisteSuccess.setMessage("Register successfully");
										
										alertDialogRegisteSuccess.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												new Thread(runnable).start();
												dialog.dismiss();
											}
										});
										
										alertDialogRegisteSuccess.setCancelable(false);
										
										
										MainActivity.this.runOnUiThread(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												AlertDialog dialogRegistSuccess = alertDialogRegisteSuccess.create();
												dialogRegistSuccess.show();
											}
										});
									}
								} catch (Exception e) {
									// TODO: handle exception
									e.printStackTrace();
								}
								return null;
							}
						};
						progressTask.execute((Void[])null);
					}
				});
			}
		};
        
        handler = new Handler();
        
        runnable = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
						View dialogView = inflater.inflate(R.layout.dialog_login, null);
						AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
						dialogBuilder.setTitle("Login");
						dialogBuilder.setView(dialogView);
						
						dialogBuilder.setOnKeyListener(new DialogInterface.OnKeyListener() {
							
							@Override
							public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
								// TODO Auto-generated method stub
								if (keyCode == KeyEvent.KEYCODE_BACK) {
									showExitConfirmDialog(TYPE_EXIT.LOGIN_DIALOG);
									dialog.dismiss();
								}
								return false;
							}
						});
						
						final AlertDialog dialog = dialogBuilder.create();
						
						Button loginButton = (Button)dialogView.findViewById(R.id.btn_login);
						Button cancelButton = (Button)dialogView.findViewById(R.id.btn_cancel);
						
						final EditText txtUserName = (EditText)dialogView.findViewById(R.id.txt_name);
						final EditText txtPassword = (EditText)dialogView.findViewById(R.id.password);
						final TextView tvRegister = (TextView)dialogView.findViewById(R.id.tw_registe);
						
						loginButton.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								
								new Thread(progRunnable).start();
								dialog.dismiss();
								User Account = new User();
								Account.setMail(txtUserName.getText().toString());
								Account.setPassword(txtPassword.getText().toString());
								checkAccount(Account);
							}
						});
						cancelButton.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								System.exit(0);
							}
						});
						
						tvRegister.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
								View dialogView = inflater.inflate(R.layout.dialog_register, null);
								AlertDialog.Builder registeBuilder = new AlertDialog.Builder(MainActivity.this);
								registeBuilder.setTitle("Register");
								registeBuilder.setView(dialogView);
								
								registeBuilder.setCancelable(false);
								
								final AlertDialog registDialog = registeBuilder.create();
								Button registButton = (Button)dialogView.findViewById(R.id.btn_registe);
								Button cancelRegistButton = (Button)dialogView.findViewById(R.id.btn_cancel_registe);
								final TextView notification = (TextView)dialogView.findViewById(R.id.tv_notification);
								final EditText edtEmail = (EditText)dialogView.findViewById(R.id.edt_email);
								final EditText edtPass = (EditText)dialogView.findViewById(R.id.edt_pass);
								final EditText edtConfirmPass = (EditText)dialogView.findViewById(R.id.edt_cfr_pass);
								
								registButton.setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										registResult = REGIST_RESULT.NONE;
										new Thread(registRunnable).start();
										for (int i = 0; i < userList.size(); i++) {
											if (userList.get(i).getMail().toString().compareTo(edtEmail.getText().toString()) == 0) {
												notification.setText("The email address is already registered");
												registResult = REGIST_RESULT.REGIST_ERROR;
												break;
											}
										}
										if (registResult != REGIST_RESULT.REGIST_ERROR) {
											if (edtPass.getText().toString().compareTo("") == 0) {
												notification.setText("Password is empty");
												registResult = REGIST_RESULT.REGIST_ERROR;
											} else {
												if (edtPass.getText().toString().compareTo(edtConfirmPass.getText().toString()) != 0) {
													notification.setText("Password does not match confirm password");
													registResult = REGIST_RESULT.REGIST_ERROR;
												} else {
													registResult = REGIST_RESULT.REGIST_SUCCESSFULLY;
													User account = new User();
													account.setMail(edtEmail.getText().toString());
													account.setPassword(edtPass.getText().toString());
												}
											}
										}
									}
								});
								
								cancelRegistButton.setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										new Thread(runnable).start();
										registDialog.dismiss();
									}
								});
								registDialog.show();
								dialog.dismiss();
							}
						});
						dialog.show();
					}
				});
			}
		};
		new Thread(runnable).start();
        
        TabHost tabHost = getTabHost();
        
        Intent intentAndroid = new Intent().setClass(this, MyLocationActivity.class);
        TabSpec tabSpecMyLocation = tabHost.newTabSpec("My Location")
                .setIndicator("My Location")
                .setContent(intentAndroid);
        
        tabHost.addTab(tabSpecMyLocation);
        
        Intent intentSearch = new Intent().setClass(this, SearchActivity.class);
        TabSpec tabSpecSearch = tabHost.newTabSpec("Search")
        .setIndicator("Search")
        .setContent(intentSearch);

        tabHost.addTab(tabSpecSearch);
        
        Intent intentInfor = new Intent().setClass(this, InformationActivity.class);
        TabSpec tabSpecInfor = tabHost.newTabSpec("Information")
        .setIndicator("Information")
        .setContent(intentInfor);

        tabHost.addTab(tabSpecInfor);
    }
    
    private void checkAccount(User user)
    {
    	for (int i = 0; i < userList.size(); i++) {
    		if ((userList.get(i).getMail().compareTo(user.getMail())) == 0) {
    			if ((userList.get(i).getPassword().compareTo(user.getPassword())) == 0) {
    				flagCheckLogin = true;
    				return;
    			}
    		}
    	}
    	flagCheckLogin = false;
    }
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showExitConfirmDialog(TYPE_EXIT.ACTIVITY);
		//super.onBackPressed();
	}

	private void showExitConfirmDialog(TYPE_EXIT type)
	{
		final TYPE_EXIT typeExit = type;
		AlertDialog.Builder exitBuilder = new AlertDialog.Builder(MainActivity.this);
		exitBuilder.setTitle("Exit");
		exitBuilder.setMessage("Are you sure you want to exit the application?");
		exitBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				MainActivity.this.finish();
			}
		});
		exitBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (typeExit == TYPE_EXIT.LOGIN_DIALOG) {
					new Thread(runnable).start();
				}
				dialog.cancel();
			}
		});
		exitBuilder.setCancelable(false);
		
		AlertDialog exitDialog = exitBuilder.create();
		exitDialog.show();
	}
    

    
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }
}
